package cn.dapeng.interview;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 延时队列
 */
public class DelayQueue_T01 {

    static BlockingQueue<Mytask> tasks = new DelayQueue<>();

    static class Mytask implements Delayed {

        String name;
        long runningTime;

        Mytask(String name, long runningTime) {
            this.name = name;
            this.runningTime = runningTime;
        }

        @Override
        public long getDelay(TimeUnit unit) {
            return unit.convert(runningTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
        }

        @Override
        public int compareTo(Delayed o) {
            return (int) (this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS));
        }

        @Override
        public String toString() {
            return "Mytask [name=" + name + ", runningTime=" + runningTime + "]";
        }
    }

    public static void main(String[] args) throws Exception {
        long now = System.currentTimeMillis();

        Mytask t1 = new Mytask("t1", now + 1000);
        Mytask t2 = new Mytask("t2", now + 2000);
        Mytask t3 = new Mytask("t3", now + 1500);
        Mytask t4 = new Mytask("t4", now + 2500);
        Mytask t5 = new Mytask("t5", now + 500);

        tasks.add(t1);
        tasks.add(t2);
        tasks.add(t3);
        tasks.add(t4);
        tasks.add(t5);

        for (int i = 0; i < 5; i++) {
            System.out.println(tasks.take());
        }

    }
}
